package org.wmq.shopmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.wmq.shopmanager.mapper.CategoryMapper;
import org.wmq.shopmanager.service.CategoryService;
import org.wmq.shopmodel.Entity.product.Category;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    private final CategoryMapper categoryMapper;

    @Override
    public List<Category> getListByParentId(Long parentId) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId,parentId);
        List<Category> result = this.list(queryWrapper);
//      result = this.categoryMapper.selectList(queryWrapper);
        if (result == null || result.isEmpty()){
            return result;
        }
        for (Category category : result){
            category.setHasChildren(!this.isLeaf(category));
        }
        return result;
    }

    private boolean isLeaf(Category category){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId,category.getParentId());
        return this.categoryMapper.selectCount(queryWrapper) == 0;
    }
}
